export default {
	namespaced: true,
	state: () => ({
		// { goods_id,goods_name,goods_price,goods_count,goods_small_logo,goods_state }
		cart: uni.getStorageSync('cart') || [], // 购物车列表
	}),
	mutations: {
		// 将商品添加购物车
		addGoodsToCart(state, goods) {
			// 查询商品是否存在
			const findGoods = state.cart.find(item => item.goods_id === goods.goods_id)
			if (findGoods) {
				// 存在 修改数量
				findGoods.goods_count++
			} else {
				state.cart.push(goods)
			}
			this.commit('m_cart/saveGoodsToStorage')
		},

		// 修改商品选中状态
		updateGoodsState(state, goods) {
			const findGoods = state.cart.find(item => item.goods_id === goods.goods_id)
			if (findGoods) {
				findGoods.goods_state = goods.goods_state
				this.commit('m_cart/saveGoodsToStorage')
			}
		},

		// 修改商品数量
		updateGoodsCount(state, goods) {
			const findGoods = state.cart.find(item => item.goods_id === goods.goods_id)
			if (findGoods) {
				findGoods.goods_count = goods.goods_count
				this.commit('m_cart/saveGoodsToStorage')
			}
		},

		// 根据ID 删除商品
		removeGoodsById(state, goods_id) {
			// 方式一
			// const i = state.cart.findIndex(item => item.goods_id === goods_id)
			// state.cart.splice(i, 1)

			// 方式二
			state.cart = state.cart.filter(item => item.goods_id !== goods_id)

			this.commit('m_cart/saveGoodsToStorage')
		},

		// 购物车数据持久化处理
		saveGoodsToStorage(state) {
			uni.setStorageSync('cart', state.cart)
		},

		// 修改所有商品选中状态
		updateAllGoodsState(state, a) {
			state.cart.forEach(item => item.goods_state = a)
			this.commit('m_cart/saveGoodsToStorage')
		}
	},
	getters: {
		// 统计商品总数量
		getAllGoodsCount(state) {
			return state.cart.reduce((total, goods) => {
				return total += goods.goods_count
			}, 0)
		},
		// 获取选中商品总数量
		getCheckdGoodsCount(state) {
			return state.cart.reduce((total, goods) => {
				// 被选中
				if (goods.goods_state) {
					return total += goods.goods_count
				}
				// 没被选中 直接return 原值
				return total
			}, 0)
		},
		// 获取选中商品总价格
		getCheckdGoodsToatlProce(state) {
			return state.cart.reduce((totalProce, goods) => {
				// 被选中
				if (goods.goods_state) {
					return totalProce += goods.goods_count * goods.goods_price
				}
				// 没被选中 直接return 原值
				return totalProce
			}, 0).toFixed(2)
		}
	},
}